#include "../myhead.h"

int main(int argc, char const *argv[])
{
    key_t key = ftok(".", 10);

    // 申请共享内存
    int shmid = shmget(key, PAGE_SIZE, IPC_CREAT | 0777);

    if (shmid == -1)
    {
        perror("shmget failed \n");
        return -1;
    }
    // 开启共享内存映射
    char *p = shmat(shmid, NULL, 0);
    if (p == (void *)-1)
    {
        perror("shmat failed \n");
        return -1;
    }

    // 申请信号量
    int semid = semget(key, 2, IPC_CREAT | 0777);

    if (semid == -1)
    {

        perror("semget failed \n");
        return -1;
    }

    // 先定义pv操作的结构体
    // p1 写 p2 读信号操作结构体
    struct sembuf p1_write;
    p1_write.sem_num = 0;
    p1_write.sem_op = 1;
    p1_write.sem_flg = SEM_UNDO;

    // p2 写 p1 读信号操作结构体
    struct sembuf p1_read;
    p1_read.sem_num = 1;
    p1_read.sem_op = -1;
    p1_read.sem_flg = SEM_UNDO;

    // 初始化值 暂定 p1 先写 p2先读
    semctl(semid, 0, SETVAL, 0);
    // 两个信号量都设为 0, 都只能写不能读
    semctl(semid, 1, SETVAL, 0);

    while (1)
    {
        // 先执行写的逻辑
        printf("请输入发送给p2的消息 \n");
        scanf("%s", p);
        semop(semid, &p1_write, 1);//进行v操作
        if(strcmp(p,"exit") == 0) {
            break;
        }
        // 等对方写
        semop(semid, &p1_read, 1);
        printf("收到p2的消息了 %s \n", p);//进行p操作
        if(strcmp(p,"exit") == 0) {
            break;
        }
    }

    shmdt(p);//解除内存映射
    shmctl(shmid, IPC_RMID, NULL);//删除共享内存
    semctl(semid, 0, IPC_RMID);//删除信号量
    return 0;
}
